<template>
  <!-- 配件盘点 -->
  <div>
    <FormPanel ref="form" :cols="3" :list="list" :isSubmitBtn="false"></FormPanel>
    <FilterTable
      ref="table"
      columnsRef="partAccessAccessInventoryIndex"
      selectionType="single"
      :isMemoryPagination="true"
      :columns="columns"
      :dataSource="dataSource"
      :onCellChange="onCellChange"
      :onSyncTableData="columns => (this.inTableListData = columns)"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="handleTableRowSelect"
    >
      <template slot="moreActions">
        <span @click="handleDeleteDetail">删除明细</span>
      </template>
      <template slot="controls">
        <!-- <el-row class="btn-wrap"> -->
        <el-button
          size="small"
          type="primary"
          :disabled="isDisabled_newPart"
          icon="el-icon-plus"
          @click="
            () => {
              this.isShowNewPart = true;
            }
          "
          >新增</el-button
        >
        <el-button
          size="small"
          type="primary"
          :disabled="isDisabled_add"
          icon="el-icon-plus"
          @click="
            () => {
              this.isShowAddPanel = true;
            }
          "
          >新建</el-button
        >
        <AjaxButton size="small" type="primary" :disabled="isDisabled_save" :click="saveBtnClick">保存</AjaxButton>
        <!-- <el-button size="small" type="primary" :disabled="isDisabled_ok" @click="confirmBtnClick">盘点确认</el-button> -->
        <!-- :style="{ display: registerBtn }" -->
        <UploadFile
          style="margin: 0 10px;"
          :initial-value="fileInitalValue"
          isOnlyButton
          :limit="20"
          :disabled="isDisabled_newPart"
          type="primary"
          icon="el-icon-download"
          :actionUrl="`${server.DMSCLOUD_PART}/basedata/ttSalesPart/importSalesPart`"
          @change="handleUploadChange"
          >导入</UploadFile
        >
        <el-button size="small" type="primary" :disabled="isDisabled_newPart" :loading="exportModelLoading" @click="exportModel">导出模板</el-button>
        <MultiuseButton size="small" type="primary" :disabled="isDisabled_ok" :auth-list="auths" auth-mark="/api/dmscloud.part/basedata/inventoryCheck/btnConfirm" @click="confirmBtnClick"
          >盘点确认</MultiuseButton
        >
        <el-button size="small" type="primary" :disabled="isDisabled_cancel" @click="cancelBtnClick">取消</el-button>
        <el-button size="small" type="primary" :disabled="isDisabled_report" @click="printOrder">打印</el-button>
        <el-button size="small" type="primary" :disabled="isDisabled_report" @click="inventoryReport">盘点报告</el-button>
        <el-button size="small" type="primary" :disabled="isDisabled_invalid" @click="invalidBtnClick">作废</el-button>

        <!-- </el-row> -->
      </template>
    </FilterTable>
    <div></div>

    <BaseDialog :visible.sync="isShowOrderSearch" title="盘点单信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OrderSearch :ptype="this.ptype" @confirm="confirmOrderSearch" @cancel="isShowOrderSearch = false"></OrderSearch>
    </BaseDialog>
    <BaseDialog :visible.sync="isShowAddPanel" title="新建配件盘点" destroyOnClose>
      <AddPanel :ptype="this.ptype" @confirm="confirmAddPanel" @cancel="isShowAddPanel = false" />
    </BaseDialog>
    <BaseDialog :visible.sync="isShowNewPart" title="新增盘点配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addNewPart @confirm="setNewPartData" @cancel="isShowNewPart = false" />
    </BaseDialog>
    <div v-if="isPrintOrder">
      <!-- templateCheckList :data="vehicledList"-->
      <BasePrint ref="printCheckList" :data="checkListData" template="templateCheckList" />
      <BasePrint ref="printCheckListHide" :data="checkListData" template="templateCheckListHide" />
    </div>
    <BasePrint ref="printCheckListReport" :data="checkListData" template="templateCheckListReport" />
  </div>
</template>

<script>
import { state, mutations } from './store';
import { dictionary } from '@/utils/dictMixin';
import { getOwnerCode, getAppId } from '@/assets/js/auth';
import {
  cancelInventoryCheck,
  confirmInventoryCheck,
  findAllInventoryItemById,
  saveInventoryInfo,
  btnDel,
  btnConfirm,
  deleteTableData,
  saveBlankInventoryNo,
  saveInventoryCheck,
  getSysParaValueByCode,
  printReport,
  deleteWholeOrder
} from '@/api/part/access/accessInventory';
import addNewPart from './addNewPart';
import AddPanel from './AddPanel';
import OrderSearch from './OrderSearch';
import moment from 'moment';
import { authority } from '@/utils/authMixin';
import * as Util from '@/utils/index.js';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { arrayObjDeWeight, confirmAction, notifyAction } from '@/utils';
import { dealerPrintApi } from '@/api/repair/index.js';
import SERVER from '@/api/server';
import { exportSalesModel } from '@/api/part/partOut/partSales/index';
import MultiuseButton from '../../../../components/MultiuseButton/MultiuseButton.vue';

export default {
  name: 'Brand',
  components: {
    addNewPart,
    AddPanel,
    OrderSearch,
    MultiuseButton
  },
  mixins: [dictionary, authority],
  data() {
    this.state = state;
    return {
      list: this.createList(),
      columns: this.createColumns(),
      columnsShow: this.createColumns(),
      columnsHidden: this.createColumnsHidden(),
      dataSource: [],
      userList: [],
      isDisabled_report: true,
      inTableListData: [],
      fileInitalValue: [],
      orderStatus: '',
      isShowAddPanel: false,
      isShowOrderSearch: false,
      isShowNewPart: false,
      selectedTableData: [],
      server: SERVER,
      exportModelLoading: false,
      /** 按钮状态 S */
      isDisabled_newPart: true,
      isDisabled_add: false,
      isDisabled_save: true,
      isDisabled_ok: false,
      isDisabled_cancel: false,
      isDisabled_print: false,
      isDisabled_invalid: false,
      /** 按钮状态 E */
      itemIds: [],
      isPrintOrder: false, // 隐藏盘点单
      checkListData: {},
      isConfirmed: false,
      isReport: false,
      // 盘点清单打印显示库存数(是否显示)
      quantityShow: true,
      // 盈亏原因是否必填
      isEnter: false,
      printParams: {} // 打印参数
    };
  },
  computed: {
    inventory_no: () => state.inventory_no, // 盘点单号
    handler: () => state.handler, // 经手人
    inventory_date: () => state.inventory_date, // 盘点日期
    remark: () => state.remark, // 备注
    ptype() {
      return this.$route.meta.ptype;
    } // 模块区分
  },
  mounted() {
    window.bjpd = this;
    this.isDisabled_add = false;
    this.isDisabled_save = true;
    this.isDisabled_ok = true;
    this.isDisabled_cancel = true;
    this.isDisabled_print = true;
    this.isDisabled_invalid = true;
    this.serachService();
    this.innerTableData = this.$refs.table.$refs.pageTable;
    this.baseTable = this.$refs.table.$refs.pageTable;
    // this.queryPrintParams();
  },
  created() {
    // this.initQuery();
    this.$nextTick(() => {
      // console.log(this.columns, '11111111111');
    });
  },
  methods: {
    // 初始化查询配件基本参数
    async initQuery() {
      // 查询系统参数
      let res = await getSysParaValueByCode({ ownerCode: getOwnerCode(), module: 'SPA', para: 'BJPDPKKZ' });
      console.log('系统参数', res);
      if (res.resultCode == 200) {
        // this.$notify.success({ title: '提示信息', message: '查询配件参数信息成功' });
        if (res.data.bParaValue == '1') {
          this.isEnter = false;
        }
      } else {
        return this.$notify.error({ title: '提示信息', message: '查询配件参数信息失败,请稍后重试' });
      }
      this.columns.find(item => item.dataIndex === 'REMARKS').editRequired = this.isEnter;
    },
    createColumnsHidden() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   width: 70,
        //   sorter: true,
        //   render: props => {
        //     return (
        //       <el-row type="flex" justify="space-around">
        //         <el-link type="primary" onClick={() => this.cellDeleteBtnClick(props.row)} disabled={this.rowDeleteBtnDisabled()}>
        //           删除
        //         </el-link>
        //       </el-row>
        //     );
        //   }
        // },

        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },

        {
          title: '清点数量',
          dataIndex: 'CHECK_QUANTITY',
          disabled: false,
          sorter: true,
          filter: true,
          editRequired: true,
          filterType: 'number',
          defaultEditable: true,
          editable: true,
          initialValue: 0,
          precision: 2,
          editPattern: /^\d+(\.\d{1,2})?$/,
          min: 0,
          editType: 'number',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },

        // {
        //   title: '含税成本单价',
        //   dataIndex: 'COST_PRICE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2,
        //   showOverflowTooltip: true,
        //   exportFormat: {
        //     t: 'n'
        //   }
        // },
        {
          title: '盈亏原因',
          dataIndex: 'REMARKS',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          editable: true,
          editType: 'input',
          defaultEditable: true
        }
      ];
    },
    createList() {
      return [
        {
          type: 'INPUT',
          label: '盘点单号',
          fieldName: 'inventoryNo',
          initialValue: '',
          readonly: false,
          unitRender: () => {
            return (
              <div>
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-search"
                  onClick={() => {
                    this.isShowOrderSearch = true;
                  }}
                ></el-button>
              </div>
            );
          }
        },
        {
          label: '是否按库存盘点',
          fieldName: 'isStockInventory',
          hidden: true,
          type: 'INPUT'
        },
        {
          type: 'SELECT',
          label: '经手人',
          fieldName: 'handler',
          placeholder: '请选择...',
          itemList: [],
          disabled: true
        },
        {
          type: 'DATE',
          label: '盘点日期',
          fieldName: 'inventoryDate',
          format: 'yyyy-MM-dd',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          initialValue: '',
          disabled: true,
          selfCols: 2
        }
      ];
    },
    // 校验表单数据是否为空
    checkTableData() {
      console.log(this.selectedTableData);
      if (this.selectedTableData.length < 1) {
        return this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      }
    },
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   width: 70,
        //   sorter: true,
        //   render: props => {
        //     return (
        //       <el-row type="flex" justify="space-around">
        //         <el-link type="primary" onClick={() => this.cellDeleteBtnClick(props.row)} disabled={this.rowDeleteBtnDisabled()}>
        //           删除
        //         </el-link>
        //       </el-row>
        //     );
        //   }
        // },

        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '账面库存',
          dataIndex: 'CURRENT_STOCK',
          sorter: true,
          filter: true,
          filterType: 'number',
          disabled: true,
          render: props => {
            return <span>{Number(props.row.CURRENT_STOCK).toFixed(2)}</span>;
          },
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },
        {
          title: '清点数量',
          dataIndex: 'CHECK_QUANTITY',
          disabled: false,
          sorter: true,
          filter: true,
          filterType: 'number',
          defaultEditable: true,
          editable: true,
          initialValue: 0,
          precision: 2,
          editPattern: /^\d+(\.\d{1,2})?$/,
          min: 0,
          editType: 'number',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },
        {
          title: '差异数量',
          dataIndex: 'PROFIT_LOSS_QUANTITY',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          render: props => {
            const checkQuantity = props.row.CHECK_QUANTITY;
            const realStock = props.row.CURRENT_STOCK;
            props.row.PROFIT_LOSS_QUANTITY = Number(checkQuantity - realStock).toFixed(2);
            // console.log(`checkQuantity:${checkQuantity}; realStock:${realStock}`)
            return <div> {props.row.PROFIT_LOSS_QUANTITY} </div>;
          },
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },
        // {
        //   title: '差异金额',
        //   dataIndex: 'PROFIT_LOSS_AMOUNT',
        //   sorter: true,
        //   filter: true,
        //   precision: 2,
        //   filterType: 'number',
        //   render: props => {
        //     const checkQuantity = props.row.CHECK_QUANTITY;
        //     const realStock = props.row.CURRENT_STOCK;
        //     const costPrice = props.row.COST_PRICE;
        //     props.row.PROFIT_LOSS_AMOUNT = Number(checkQuantity - realStock).toFixed(2) * Number(costPrice.toFixed(2));
        //     // console.log(`checkQuantity:${checkQuantity}; realStock:${realStock}`)
        //     return <div> {props.row.PROFIT_LOSS_AMOUNT} </div>;
        //   },
        //   showOverflowTooltip: true,
        //   exportFormat: {
        //     t: 'n'
        //   }
        // },
        // {
        //   title: '含税成本单价',
        //   dataIndex: 'COST_PRICE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2,
        //   showOverflowTooltip: true,
        //   exportFormat: {
        //     t: 'n'
        //   }
        // },
        {
          title: '盈亏原因',
          dataIndex: 'REMARKS',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          defaultEditable: true,
          editable: true,
          editType: 'input'
        }
      ];
    },

    async confirmOrderSearch(row) {
      console.log('盘点单搜索 confirm', row);
      if (row.ORDER_STATUS == '91951002') {
        this.columns = this.columnsHidden;
      } else {
        this.columns = this.columnsShow;
      }
      this.isShowOrderSearch = false;
      this.list.find(x => x.fieldName === 'inventoryNo').initialValue = row.INVENTORY_NO;
      this.list.find(x => x.fieldName === 'inventoryNo').disabled = true;

      this.list.find(x => x.fieldName === 'handler').initialValue = +row.HANDLER;
      this.list.find(x => x.fieldName === 'inventoryDate').initialValue = row.INVENTORY_DATE;
      this.list.find(x => x.fieldName === 'remark').initialValue = row.REMARK;
      this.list.find(x => x.fieldName === 'isStockInventory').initialValue = row.IS_STOCK_INVENTORY;
      // 是否已盘点
      const is_confirmed = row.IS_CONFIRMED == 10041001;
      //是否已入账
      const is_finished = row.IS_FINISHED == 10041001;
      const is_report = row.IS_REPORT == 10041001;
      this.isConfirmed = is_confirmed;
      this.isReport = is_report;
      console.log('是否已盘点', is_confirmed);
      this.isDisabled_add = true;
      if (is_confirmed || is_report) {
        this.isDisabled_newPart = true;
        this.columns.find(x => x.dataIndex === 'REMARKS').disabled = true;
      } else {
        this.isDisabled_newPart = false;
      }
      this.isDisabled_save = false;
      this.isDisabled_ok = true;
      this.isDisabled_report = false;
      this.isDisabled_cancel = false;
      this.isDisabled_print = false;
      this.isDisabled_invalid = false;
      if (is_confirmed || is_report) {
        this.isDisabled_save = true;
        this.isDisabled_ok = true;
        this.isDisabled_invalid = true;
        this.columns.forEach(x => {
          if (x.dataIndex === 'CHECK_QUANTITY') {
            x.disabled = true;
          }
        });
      }
      if (row.IS_STOCK_INVENTORY == '10041001') {
        this.isDisabled_newPart = true;
      }
      const res = await findAllInventoryItemById(row.INVENTORY_NO);
      console.log('查询盘点', res.data);
      if (is_finished) {
        res.data.forEach(item => {
          item.CURRENT_STOCK = item.STOCK_QUANTITY;
        });
      }
      this.orderStatus = row.ORDER_STATUS;
      this.dataSource = res.data;
    },
    // 新建 确认 过来
    async confirmAddPanel(data) {
      console.log('新建配件盘点 confirm', data);
      if (data.isBlank != 'isBlank') {
        this.isDisabled_newPart = true;
        this.$alert(`生成${data.all.length}个盘点单：${data.all.join('、')}`, '提示信息', {
          confirmButtonText: '确定'
        });
      }

      const { inventory_no, handler, inventory_date, remark, order_status } = data;
      this.list.find(x => x.fieldName === 'inventoryNo').initialValue = inventory_no;
      this.list.find(x => x.fieldName === 'inventoryNo').disabled = true;

      this.list.find(x => x.fieldName === 'handler').initialValue = +handler;
      this.list.find(x => x.fieldName === 'inventoryDate').initialValue = inventory_date;
      this.list.find(x => x.fieldName === 'remark').initialValue = remark;

      if (data.isBlank == 'isBlank') {
        this.isDisabled_newPart = false;
      }
      this.isShowAddPanel = false;
      this.isDisabled_add = true;
      this.isDisabled_save = false;
      this.isDisabled_ok = true;
      this.isDisabled_cancel = false;
      this.isDisabled_print = false;
      this.isDisabled_invalid = false;

      const res = await findAllInventoryItemById(inventory_no);
      console.log('查询盘点', res);
      res.data.forEach(item => {
        if (order_status != '91951002') {
          item.CHECK_QUANTITY = item.CURRENT_STOCK;
        } else {
          item.CHECK_QUANTITY = 0;
        }
      });
      this.orderStatus = order_status;
      if (order_status == '91951002') {
        this.columns = this.columnsHidden;
      } else {
        this.columns = this.columnsShow;
      }
      this.dataSource = res.data;
    },
    cellDeleteBtnClick(row) {
      // console.log('cellDeleteBtnClick');
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(() => {
          this.itemIds.push(row.ITEM_ID);
          // this.dataSource.splice(row.ITEM_ID, 1);
          this.baseTable.EXECUTE_DELETE([row]);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.isDisabled_save = false;
          console.log(this.itemIds, '删除的ID');
        })
        .catch(() => {});
    },
    cellEditBtnClick(props) {
      console.log('cellEditBtnClick');
    },
    // 打印盘点单
    async printOrder() {
      // 查询系统参数
      // let res = await getSysParaValueByCode({ ownerCode: getOwnerCode(), module: 'SPA', para: 'PDQDXSKCS' });
      // console.log('系统参数', res);
      // if (res.resultCode == 200) {
      //   // this.$notify.success({ title: '提示信息', message: '获取配件参数信息成功' });
      //   if (res.data.bParaValue == 1) {
      //     this.quantityShow = false;
      //   } else {
      //     this.quantityShow = true;
      //   }
      // } else {
      //   return this.$notify.error({ title: '提示信息', message: '查询配件参数信息失败,请稍后重试' });
      // }
      this.checkListData.quantityShow = this.quantityShow;
      this.checkListData.appId = getAppId();
      this.isPrintOrder = true;
      // this.list.find(x => x.fieldName === 'remark').initialValue
      this.checkListData['inventoryNo'] = this.list.find(x => x.fieldName === 'inventoryNo').initialValue;
      this.checkListData['handler'] = this.userList.find(x => x.value == this.list.find(x => x.fieldName === 'handler').initialValue).text;
      if (this.list.find(x => x.fieldName === 'inventoryDate').initialValue !== '' || this.list.find(x => x.fieldName === 'inventoryDate').initialValue !== null) {
        this.checkListData['inventoryDate'] = moment(this.list.find(x => x.fieldName === 'inventoryDate').initialValue).format('YYYY-MM-DD HH:mm:ss');
      } else {
        this.checkListData['inventoryDate'] = '';
      }
      this.checkListData['remark'] = this.list.find(x => x.fieldName === 'remark').initialValue;
      // console.log('盘点打印', this.dataSource);

      this.checkListData['inventoryList'] = this.dataSource;
      this.$nextTick(() => {
        if (this.orderStatus == '91951002') {
          this.$refs.printCheckListHide.EXCUTE_PRINT();
        } else {
          this.$refs.printCheckList.EXCUTE_PRINT();
        }
      });
    },
    // 表格里 删除 按钮 禁用
    rowDeleteBtnDisabled() {
      if (this.isConfirmed) {
        return true;
      }
      return false;
    },
    setNewPartData(val) {
      // debugger;
      for (let i = 0; i < this.inTableListData.length; i++) {
        if (this.inTableListData[i].PART_NO == val.PART_NO && this.inTableListData[i].STORAGE_CODE == val.STORAGE_CODE) {
          this.$notify({ title: '警告信息', message: '相同配件不可以重复添加！', type: 'warning' });
          return;
        }
      }
      if (this.orderStatus == '91951002') {
        val.CHECK_QUANTITY = 0;
      }
      this.baseTable.EXECUTE_INSERT(val);
      this.$notify({ title: '提示', message: '添加成功', type: 'success' });
      this.baseTable.EXECUTE_RESET_HEIGHT();
      this.isDisabled_save = false;
      this.isDisabled_ok = true;
      // 添加回显
    },
    onCellChange(val, val2) {
      this.isDisabled_save = false;
      this.isDisabled_ok = true;
    },
    // 保存 按钮
    async saveBtnClick() {
      if (this.isConfirmed || this.isReport) {
        this.$notify.warning({
          title: '提示信息',
          message: '已盘点确认或报告无法保存'
        });
        return;
      }
      const [err, params] = await this.$refs.form.GET_FORM_DATA();
      let errTab = await this.$refs.table.GET_REQUIRED_ERROR();
      // 保存校验
      if (err || errTab) {
        return;
      }
      // console.log(params, '123231');

      // this.checkTableData();
      // console.log(this.inTableListData);
      // try {
      //   if (this.inTableListData && this.inTableListData.length) {
      //     this.inTableListData.forEach(e => {
      //       if (e.PROFIT_LOSS_QUANTITY != 0 && !e.REMARKS) {
      //         throw new Error();
      //       }
      //     });
      //   }
      // } catch (Error) {
      //   return notifyAction('请输入差异数量不为0配件的盈亏原因', 'warning');
      // }

      // 校验是否选中
      // this.checkTableData();
      // if (this.selectedTableData.length < 1) {
      //   return this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      // }
      // if (this.inTableListData == null || this.inTableListData == '' || this.inTableListData == undefined) {
      //   return this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      // }
      console.log('继续执行');

      if (this.itemIds.length !== 0) {
        // params.push({'ids':this.itemIds})
        params['ids'] = this.itemIds;
        params['isStockInventory'] = 10041001;
      }
      // console.log('保存 data', this.dataSource, this.inTableListData);
      // params.dms_details = this.dataSource && this.dataSource.length ? this.dataSource : this.inTableListData;
      params.dms_details = this.inTableListData;
      // console.log('保存 params', params);
      const res_save = await saveInventoryCheck(params);
      console.log('保存 事件', res_save);
      if (res_save.resultCode == 200 && res_save.data) {
        this.$notify.success({
          title: '提示信息',
          message: '保存成功',
          type: 'success'
        });
        this.isDisabled_add = true;
        this.isDisabled_save = true;
        this.isDisabled_cancel = false;
        this.isDisabled_print = false;
        this.isDisabled_invalid = false;
        this.isDisabled_report = false;
        const res_query = await findAllInventoryItemById(res_save.data);
        console.log('查询盘点', res_query);
        this.dataSource = res_query.data;
        this.itemIds = []; // 清除删除的ID
      }
    },
    // 盘点确认 按钮
    async confirmBtnClick() {
      const inventoryNo = this.list.find(x => x.fieldName === 'inventoryNo').initialValue;
      if (!this.inTableListData || this.inTableListData.length <= 0) {
        this.$notify.warning({
          title: '提示信息',
          message: '无法盘点确认空盘点单'
        });
        return;
      }
      const res_confirm = await confirmInventoryCheck({ inventoryNo });
      console.log('盘点确认', res_confirm);
      if (res_confirm.resultCode == 200 && res_confirm.data) {
        this.$notify.success({
          title: '提示信息',
          message: '盘点确认成功'
        });
        console.log('盘点确认成功');
        // this.cancelBtnClick();
        this.itemIds = []; // 清除删除的ID
      }
    },
    async cancelBtnClick() {
      this.isDisabled_newPart = true;
      this.isDisabled_add = false;
      this.isDisabled_save = true;
      this.isDisabled_ok = true;
      this.isDisabled_cancel = true;
      this.isDisabled_print = true;
      this.isDisabled_invalid = true;
      this.isDisabled_report = true;
      this.isConfirmed = false;
      this.isReport = false;
      this.dataSource = [];
      this.list.find(x => x.fieldName === 'inventoryNo').initialValue = '';
      this.list.find(x => x.fieldName === 'handler').initialValue = '';
      this.list.find(x => x.fieldName === 'inventoryDate').initialValue = '';
      this.list.find(x => x.fieldName === 'inventoryNo').disabled = false;
      this.list.find(x => x.fieldName === 'remark').initialValue = '';
      this.columns.forEach(x => {
        if (x.dataIndex === 'CHECK_QUANTITY') {
          x.disabled = false;
        }
      });
      this.itemIds = []; // 清除删除的ID
    },
    // 配件导入成功事件
    handleUploadChange(e) {
      if (e != 1) {
        this.fileInitalValue = e;
        let excelData = _.cloneDeep(e[e.length - 1].url.result);
        console.log(excelData, 'excelData');
        if (excelData.length) {
          this.formatPartsData(excelData);
        }
        this.handleDetailSelectConfirm(excelData, e[e.length - 1].url.errorList);
      }
    },
    formatPartsData(list) {
      list.map((item, index) => {
        // this.$set(list[index], 'IN_QUANTITY', item.PART_QUANTITY);
        this.$set(list[index], 'CHECK_QUANTITY', item.PART_QUANTITY);
        this.$set(list[index], 'CURRENT_STOCK', item.STOCK_QUANTITY);
      });
    },
    handleDetailSelectConfirm(e, data) {
      let partList = e;
      // 校验重复配件
      let newPartArr = [],
        repeatingPartArr = []; // 重复配件，新配件
      console.log('datasource::', this.dataSource);
      console.log('partList::', partList);
      partList.map(item => {
        if (this.dataSource.find(x => x.partNo == item.partNo)) {
          repeatingPartArr.push(item);
        } else {
          newPartArr.push(item);
        }
      });
      if (repeatingPartArr.length) {
        let idsArr = repeatingPartArr.map(item => item.PART_NO);
        notifyAction('配件代码：' + idsArr.join(',') + '已存在', 'warning');
      }
      newPartArr = JSON.parse(JSON.stringify(newPartArr)); // 浅拷贝防止原始数据修改
      this.formatPartsData(newPartArr);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(newPartArr);
      if (data.length > 0) {
        let errorData = data.map(x => {
          return '仓库：' + x.storageCode + '中配件：' + x.partNo + '不存在';
        });
        this.$notify.warning({ title: '提示信息', message: `导入成功，${errorData.join('，')}，请确认模板` });
      } else {
        notifyAction('配件导入成功', 'success');
      }
    },
    exportModel() {
      this.exportModelLoading = true;
      exportSalesModel().then(res => {
        console.log('res:::', res);
        Util.exportExcelFile(res.data, '配件盘点模板');
        this.exportModelLoading = false;
      });
    },
    invalidBtnClick() {
      // if (this.inTableListData == null || this.inTableListData == '' || this.inTableListData == undefined) {
      //   return this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      // }
      let inventoryNo = this.list.find(x => x.fieldName === 'inventoryNo').initialValue;
      if (!inventoryNo) return;
      this.$confirm('是否作废本盘点单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await cancelInventoryCheck({ inventoryNo });
          // console.log('盘点作废', res);
          if (res.resultCode == 200) {
            console.log('盘点作废成功');
            this.$notify.success({
              title: '提示信息',
              message: '作废成功'
            });
            this.cancelBtnClick();
            this.itemIds = []; // 清除删除的ID
          }
        })
        .catch(() => {});
    },
    async serachService() {
      let res = await getAllUser();
      let dataList = arrayObjDeWeight(res.data, 'userId');
      this.userList = dataList.map(x => ({ text: x.employeeName, value: x.userId }));
      this.list.find(x => x.fieldName === 'handler').itemList = dataList.map(x => ({ text: x.employeeName, value: x.userId }));
    },
    async inventoryReport() {
      this.checkListData['inventoryNo'] = this.list.find(x => x.fieldName === 'inventoryNo').initialValue;
      let res = await printReport({ inventoryNo: this.checkListData['inventoryNo'] });
      if (res.resultCode == 200) {
        this.checkListData['handler'] = this.userList.find(x => x.value == this.list.find(x => x.fieldName === 'handler').initialValue).text;
        if (this.list.find(x => x.fieldName === 'inventoryDate').initialValue !== '' || this.list.find(x => x.fieldName === 'inventoryDate').initialValue !== null) {
          this.checkListData['inventoryDate'] = moment(this.list.find(x => x.fieldName === 'inventoryDate').initialValue).format('YYYY-MM-DD HH:mm:ss');
        } else {
          this.checkListData['inventoryDate'] = '';
        }
        this.checkListData['remark'] = this.list.find(x => x.fieldName === 'remark').initialValue;
        // console.log('盘点打印', this.dataSource);
        let dataSource = JSON.parse(JSON.stringify(this.dataSource));
        let res = dataSource.filter(x => x.PROFIT_LOSS_QUANTITY != 0);
        this.checkListData['inventoryList'] = res;
        this.checkListData.appId = getAppId();
        this.$nextTick(() => {
          this.$refs.printCheckListReport.EXCUTE_PRINT();
        });
        this.isDisabled_ok = false;
        this.columns.find(x => x.dataIndex == 'CHECK_QUANTITY').disabled = true;
        this.columns.find(x => x.dataIndex == 'REMARKS').disabled = true;
        this.isReport = true;
        const res_query = await findAllInventoryItemById(this.checkListData['inventoryNo']);
        console.log('查询盘点', res_query);
        this.dataSource = res_query.data;
        this.itemIds = []; // 清除删除的ID
      }
    },
    // table行项选中
    handleTableRowSelect(e) {
      this.selectedTableData = e;
    },
    // 点击更多操作中的删除
    handleDeleteDetail() {
      // console.log(this.selectedTableData);
      if (this.isConfirmed) {
        this.$notify.warning({
          title: '提示信息',
          message: '已盘点确认无法删除'
        });
        return;
      }
      if (this.isReport) {
        this.$notify.warning({
          title: '提示信息',
          message: '已盘点报告无法删除'
        });
        return;
      }
      console.log('ssssssssss:', this.list.find(x => x.fieldName === 'isStockInventory').initialValue);
      if (this.list.find(x => x.fieldName === 'isStockInventory').initialValue === 10041001) {
        this.$notify.warning({
          title: '提示信息',
          message: '按仓库盘点无法删除明细'
        });
        return;
      } else {
        this.cellDeleteBtnClick(this.selectedTableData[0]);
      }
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJPD'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style lang="less" scoped>
.btn-wrap {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
}
</style>
